<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>跑单评价详情 - 跑单评价系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Arial', sans-serif;
            background-color: #f8f9fa;
            color: #333;
            line-height: 1.6;
        }

        .header {
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .header h1 {
            color: #2c3e50;
            font-size: 24px;
        }

        .header .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .header .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #3498db;
        }

        .header .logout {
            background-color: #e74c3c;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        .header .logout:hover {
            background-color: #c0392b;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 40px 20px;
        }

        .page-header {
            margin-bottom: 30px;
        }

        .page-title {
            color: #2c3e50;
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 20px;
        }

        .breadcrumb {
            display: flex;
            align-items: center;
            gap: 10px;
            color: #7f8c8d;
            font-size: 14px;
        }

        .breadcrumb a {
            color: #3498db;
            text-decoration: none;
            transition: color 0.3s;
        }

        .breadcrumb a:hover {
            color: #2980b9;
        }

        .breadcrumb .separator {
            color: #bdc3c7;
        }

        /* 跑单详情卡片 */
        .order-details-card {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            padding: 30px;
            margin-bottom: 30px;
        }

        .order-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }

        .order-info h2 {
            font-size: 24px;
            color: #2c3e50;
            margin-bottom: 10px;
        }

        .order-status {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 16px;
            color: #2c3e50;
        }

        .status-badge {
            padding: 6px 15px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
        }

        .status-completed {
            background-color: #e8f5e9;
            color: #43a047;
        }

        .order-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .info-item {
            display: flex;
            flex-direction: column;
        }

        .info-label {
            font-size: 14px;
            color: #7f8c8d;
            margin-bottom: 5px;
        }

        .info-value {
            font-size: 16px;
            font-weight: 500;
            color: #2c3e50;
        }

        /* 评价详情 */
        .review-details-card {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            padding: 30px;
            margin-bottom: 30px;
        }

        .card-title {
            font-size: 20px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .review-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 20px;
        }

        .reviewer-info {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .reviewer-avatar {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            background-color: #3498db;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            font-weight: 600;
        }

        .reviewer-details h3 {
            font-size: 18px;
            color: #2c3e50;
            margin-bottom: 5px;
        }

        .reviewer-level {
            display: inline-block;
            background-color: #fff3e0;
            color: #fb8c00;
            padding: 3px 10px;
            border-radius: 12px;
            font-size: 12px;
            margin-bottom: 10px;
        }

        .review-date {
            color: #7f8c8d;
            font-size: 14px;
        }

        .rating {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 10px;
        }

        .rating-score {
            font-size: 36px;
            font-weight: 700;
            color: #f39c12;
        }

        .rating-stars {
            font-size: 24px;
            color: #f39c12;
        }

        .review-content {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 16px;
            line-height: 1.8;
            color: #555;
        }

        .review-tags {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }

        .review-tag {
            background-color: #e3f2fd;
            color: #1976d2;
            padding: 5px 15px;
            border-radius: 15px;
            font-size: 14px;
        }

        .review-media {
            margin-bottom: 20px;
        }

        .media-title {
            font-size: 16px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 15px;
        }

        .media-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 15px;
        }

        .media-item {
            width: 100%;
            aspect-ratio: 1;
            border-radius: 8px;
            overflow: hidden;
            cursor: pointer;
            transition: transform 0.3s;
        }

        .media-item:hover {
            transform: scale(1.05);
        }

        .media-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        /* 无评价状态 */
        .no-review {
            text-align: center;
            padding: 60px 20px;
            color: #7f8c8d;
        }

        .no-review-icon {
            font-size: 64px;
            margin-bottom: 20px;
            color: #bdc3c7;
        }

        .no-review h3 {
            font-size: 20px;
            margin-bottom: 10px;
            color: #2c3e50;
        }

        .no-review p {
            margin-bottom: 20px;
            font-size: 16px;
        }

        .add-review-btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .add-review-btn:hover {
            background-color: #2980b9;
        }

        /* 评价表单样式 */
        .review-form {
            display: none;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            padding: 30px;
            margin-bottom: 30px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            font-size: 16px;
            font-weight: 500;
            color: #2c3e50;
            margin-bottom: 10px;
        }

        /* 星级评分 */
        .star-rating {
            display: flex;
            gap: 10px;
            font-size: 32px;
            cursor: pointer;
        }

        .star-rating .star {
            color: #ddd;
            transition: color 0.3s;
        }

        .star-rating .star.active {
            color: #f39c12;
        }

        .star-rating .star:hover, .star-rating .star:hover ~ .star {
            color: #f39c12;
        }

        /* 评价标签 */
        .review-tags-container {
            margin-bottom: 10px;
        }

        .review-tags-label {
            display: block;
            font-size: 16px;
            font-weight: 500;
            color: #2c3e50;
            margin-bottom: 10px;
        }

        .tag-options {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .tag-option {
            padding: 8px 16px;
            border: 1px solid #ddd;
            border-radius: 20px;
            background-color: #fff;
            color: #666;
            cursor: pointer;
            transition: all 0.3s;
        }

        .tag-option:hover {
            border-color: #3498db;
            color: #3498db;
        }

        .tag-option.selected {
            background-color: #3498db;
            border-color: #3498db;
            color: white;
        }

        /* 评价内容 */
        .review-textarea {
            width: 100%;
            min-height: 150px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            font-family: inherit;
            resize: vertical;
        }

        .review-textarea:focus {
            outline: none;
            border-color: #3498db;
        }

        /* 图片上传 */
        .image-upload {
            position: relative;
            width: 120px;
            height: 120px;
            border: 2px dashed #ddd;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s;
        }

        .image-upload:hover {
            border-color: #3498db;
        }

        .image-upload input[type="file"] {
            position: absolute;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }

        .image-upload-icon {
            font-size: 24px;
            color: #ddd;
        }

        .image-preview {
            display: flex;
            gap: 15px;
            margin-top: 15px;
        }

        .preview-item {
            position: relative;
            width: 120px;
            height: 120px;
            border-radius: 8px;
            overflow: hidden;
        }

        .preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .remove-image {
            position: absolute;
            top: 5px;
            right: 5px;
            width: 24px;
            height: 24px;
            background-color: rgba(231, 76, 60, 0.8);
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
        }

        /* 表单按钮 */
        .form-actions {
            display: flex;
            gap: 15px;
            justify-content: flex-end;
            margin-top: 30px;
        }

        .btn {
            padding: 10px 25px;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background-color: #3498db;
            color: white;
        }

        .btn-primary:hover {
            background-color: #2980b9;
        }

        .btn-secondary {
            background-color: #ecf0f1;
            color: #2c3e50;
        }

        .btn-secondary:hover {
            background-color: #bdc3c7;
        }

        /* 操作按钮 */
        .action-buttons {
            display: flex;
            gap: 15px;
            margin-top: 30px;
        }

        .footer {
            background-color: #2c3e50;
            color: white;
            text-align: center;
            padding: 20px;
            margin-top: 40px;
        }

        /* 错误提示 */
        .error-message {
            background-color: #ffebee;
            color: #c62828;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            display: none;
        }

        /* 加载状态 */
        .loading {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 40px;
            color: #7f8c8d;
        }

        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @media (max-width: 768px) {
            .container {
                padding: 20px;
            }
            
            .page-title {
                font-size: 24px;
            }
            
            .order-header {
                flex-direction: column;
                gap: 20px;
            }
            
            .review-header {
                flex-direction: column;
                gap: 20px;
                align-items: flex-start;
            }
            
            .rating {
                align-items: flex-start;
            }
            
            .action-buttons,
            .form-actions {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
            }
            
            .star-rating {
                font-size: 24px;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>跑单评价系统</h1>
        <div class="user-info">
            <img id="userAvatar" src="/file/default-avatar.png" alt="用户头像" class="user-avatar">
            <form th:action="@{/logout}" method="get">
                <button type="submit" class="logout">退出登录</button>
            </form>
        </div>
    </div>

    <div class="container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="breadcrumb">
                <a href="/reviews">跑单记录</a>
                <span class="separator">/</span>
                <span>评价详情</span>
            </div>
            <h1 class="page-title">跑单评价详情</h1>
        </div>

        <!-- 错误提示区域 -->
        <div id="errorContainer" class="error-message">
            <span id="errorMessage"></span>
        </div>

        <!-- 跑单详情卡片 -->
        <div class="order-details-card" id="orderDetailsCard">
            <div class="loading">
                <div class="loading-spinner"></div>
                <p>加载跑单信息中...</p>
            </div>
        </div>

        <!-- 评价详情卡片 -->
        <div class="review-details-card" id="reviewDetailsCard">
            <h2 class="card-title">用户评价</h2>
            
            <!-- 有评价的情况 -->
            <div class="review-content-wrapper" id="reviewContentWrapper">
                <div class="loading">
                    <div class="loading-spinner"></div>
                    <p>加载评价信息中...</p>
                </div>
            </div>

            <!-- 无评价的情况 (默认隐藏) -->
            <div class="no-review" id="noReviewSection" style="display:none;">
                <div class="no-review-icon">📝</div>
                <h3>暂无评价</h3>
                <p>该跑单还没有收到评价</p>
                <button class="add-review-btn" onclick="showReviewForm()">添加评价</button>
            </div>
        </div>

        <!-- 评价表单 (默认隐藏) -->
        <div class="review-form" id="reviewForm">
            <h2 class="card-title">添加评价</h2>
            
            <!-- 评分 -->
            <div class="form-group">
                <label class="form-label">服务评分</label>
                <div class="star-rating" id="starRating">
                    <span class="star" data-rating="1">★</span>
                    <span class="star" data-rating="2">★</span>
                    <span class="star" data-rating="3">★</span>
                    <span class="star" data-rating="4">★</span>
                    <span class="star" data-rating="5">★</span>
                </div>
                <input type="hidden" id="ratingValue" value="0">
            </div>

            <!-- 评价标签 -->
            <div class="review-tags-container">
                <label class="review-tags-label">评价标签（可多选）</label>
                <div class="tag-options">
                    <span class="tag-option" data-tag="准时送达">准时送达</span>
                    <span class="tag-option" data-tag="服务态度好">服务态度好</span>
                    <span class="tag-option" data-tag="包裹完好">包裹完好</span>
                    <span class="tag-option" data-tag="沟通及时">沟通及时</span>
                    <span class="tag-option" data-tag="配送迅速">配送迅速</span>
                    <span class="tag-option" data-tag="专业高效">专业高效</span>
                    <span class="tag-option" data-tag="礼貌热情">礼貌热情</span>
                    <span class="tag-option" data-tag="值得推荐">值得推荐</span>
                </div>
                <input type="hidden" id="selectedTags" value="">
            </div>

            <!-- 评价内容 -->
            <div class="form-group">
                <label class="form-label" for="reviewContent">评价内容</label>
                <textarea class="review-textarea" id="reviewContent" placeholder="请输入您的评价内容..."></textarea>
            </div>

            <!-- 图片上传 -->
            <div class="form-group">
                <label class="form-label">上传图片（可选）</label>
                <div class="image-upload">
                    <input type="file" id="imageUpload" accept="image/*" multiple>
                    <div class="image-upload-icon">📷</div>
                </div>
                <div class="image-preview" id="imagePreview"></div>
            </div>

            <!-- 表单按钮 -->
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="hideReviewForm()">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitReview()">提交评价</button>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <button class="btn btn-primary">联系用户</button>
            <button class="btn btn-secondary" onclick="goBack()">返回列表</button>
        </div>
    </div>

    <div class="footer">
        <p>&copy; 2024 跑单评价管理系统. 保留所有权利.</p>
    </div>

    <script>
        // 从Cookie中获取JWT token
        function getJwtToken() {
            const cookieValue = document.cookie
                .split('; ')    
                .find(row => row.startsWith('jwtToken='))
                ?.split('=')[1];
            return cookieValue ? decodeURIComponent(cookieValue) : null;
        }

        // 创建带JWT token的fetch请求
        function fetchWithAuth(url, options = {}) {
            const token = getJwtToken();
            const headers = {
                ...options.headers
            };
            
            // 如果不是FormData，添加Content-Type
            if (!options.body || !(options.body instanceof FormData)) {
                headers['Content-Type'] = 'application/json';
            }
            
            if (token) {
                headers['Authorization'] = `Bearer ${token}`;
            }
            
            return fetch(url, {
                ...options,
                headers
            });
        }
        
        // 获取并显示当前用户信息和头像
        async function fetchCurrentUserInfo() {
            try {
                const response = await fetchWithAuth('/api/user/profile');
                if (!response.ok) {
                    throw new Error('获取用户信息失败');
                }
                
                const responseData = await response.json();
                console.log('用户信息响应:', responseData);
                
                // 提取用户信息，适配后端返回的格式
                const userInfo = responseData.success && responseData.data ? responseData.data : {};
                
                // 处理头像显示
                const avatarElement = document.getElementById('userAvatar');
                if (avatarElement) {
                    let avatarPath = '/file/default-avatar.png'; // 默认头像
                    
                    if (userInfo.avatar) {
                        // 如果是完整的HTTP URL，直接使用
                        if (userInfo.avatar.startsWith('http')) {
                            avatarPath = userInfo.avatar;
                        } else {
                            // 否则添加/file/前缀
                            avatarPath = `/file/${userInfo.avatar}`;
                        }
                    }
                    
                    console.log('设置头像路径:', avatarPath);
                    avatarElement.src = avatarPath;
                    avatarElement.alt = userInfo.username || '用户头像';
                }
            } catch (error) {
                console.error('获取用户信息时发生错误:', error);
                // 出错时使用默认头像
                const avatarElement = document.getElementById('userAvatar');
                if (avatarElement) {
                    avatarElement.src = '/file/default-avatar.png';
                }
            }
        }

        // 显示错误信息
        function showError(message) {
            const errorContainer = document.getElementById('errorContainer');
            const errorMessage = document.getElementById('errorMessage');
            errorMessage.textContent = message;
            errorContainer.style.display = 'block';
            
            // 3秒后自动隐藏错误信息
            setTimeout(() => {
                errorContainer.style.display = 'none';
            }, 3000);
        }

        // 返回列表
        function goBack() {
            window.location.href = '/reviews';
        }

        // 联系用户按钮（模拟）
        document.querySelector('.btn-primary').addEventListener('click', function() {
            alert('正在连接用户...');
        });

        // 显示评价表单
        function showReviewForm() {
            document.getElementById('noReviewSection').style.display = 'none';
            document.getElementById('reviewForm').style.display = 'block';
        }

        // 隐藏评价表单
        function hideReviewForm() {
            document.getElementById('reviewForm').style.display = 'none';
            document.getElementById('noReviewSection').style.display = 'block';
        }

        // 星级评分功能
        const stars = document.querySelectorAll('.star');
        const ratingValue = document.getElementById('ratingValue');
        
        stars.forEach(star => {
            star.addEventListener('click', function() {
                const rating = parseInt(this.getAttribute('data-rating'));
                ratingValue.value = rating;
                
                // 更新星级显示
                stars.forEach(s => {
                    if (parseInt(s.getAttribute('data-rating')) <= rating) {
                        s.classList.add('active');
                    } else {
                        s.classList.remove('active');
                    }
                });
            });
        });

        // 标签选择功能
        const tagOptions = document.querySelectorAll('.tag-option');
        const selectedTags = document.getElementById('selectedTags');
        const selectedTagsArray = [];
        
        tagOptions.forEach(tag => {
            tag.addEventListener('click', function() {
                const tagText = this.getAttribute('data-tag');
                const index = selectedTagsArray.indexOf(tagText);
                
                if (index === -1) {
                    // 添加标签
                    selectedTagsArray.push(tagText);
                    this.classList.add('selected');
                } else {
                    // 移除标签
                    selectedTagsArray.splice(index, 1);
                    this.classList.remove('selected');
                }
                
                selectedTags.value = selectedTagsArray.join(',');
            });
        });

        // 页面加载完成后获取用户头像
        document.addEventListener('DOMContentLoaded', function() {
            fetchCurrentUserInfo();
        });
        
        // 图片上传预览
        const imageUpload = document.getElementById('imageUpload');
        const imagePreview = document.getElementById('imagePreview');
        const uploadedImages = [];
        
        imageUpload.addEventListener('change', function() {
            const files = this.files;
            
            for (let i = 0; i < files.length; i++) {
                if (uploadedImages.length >= 5) {
                    showError('最多只能上传5张图片');
                    break;
                }
                
                const file = files[i];
                if (!file.type.startsWith('image/')) continue;
                
                uploadedImages.push(file);
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    const previewItem = document.createElement('div');
                    previewItem.className = 'preview-item';
                    previewItem.innerHTML = `
                        <img src="${e.target.result}" alt="预览图片">
                        <button class="remove-image" onclick="removeImage(this, ${uploadedImages.length - 1})">&times;</button>
                    `;
                    imagePreview.appendChild(previewItem);
                };
                reader.readAsDataURL(file);
            }
            
            // 清空input，允许重复选择相同文件
            this.value = '';
        });

        // 移除图片
        function removeImage(element, index) {
            uploadedImages.splice(index, 1);
            element.closest('.preview-item').remove();
            
            // 更新所有删除按钮的索引
            const removeButtons = document.querySelectorAll('.remove-image');
            removeButtons.forEach((btn, i) => {
                btn.setAttribute('onclick', `removeImage(this, ${i})`);
            });
        }

        // 提交评价
        async function submitReview() {
            const runOrderId = getRunOrderId();
            const rating = ratingValue.value;
            const content = document.getElementById('reviewContent').value;
            const tags = selectedTags.value;
            
            // 表单验证
            if (!rating || rating == 0) {
                showError('请选择服务评分');
                return;
            }
            
            if (!content || content.trim().length < 5) {
                showError('评价内容至少需要5个字符');
                return;
            }
            
            // 创建FormData对象
            const formData = new FormData();
            formData.append('runOrderId', runOrderId);
            formData.append('rating', rating);
            formData.append('content', content);
            formData.append('tags', tags);
            
            // 添加图片
            uploadedImages.forEach((image, index) => {
                formData.append('images', image);
            });
            
            try {
                const response = await fetchWithAuth('/api/reviews', {
                    method: 'POST',
                    body: formData
                });
                
                if (!response.ok) {
                    throw new Error('提交评价失败');
                }
                
                const result = await response.json();
                if (result.success) {
                    alert('评价提交成功！');
                    // 重新加载评价数据
                    loadReviewData();
                } else {
                    showError(result.message || '提交评价失败');
                }
            } catch (error) {
                console.error('提交评价出错:', error);
                showError('提交评价失败，请稍后重试');
            }
        }

        // 获取跑单号
        function getRunOrderId() {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get('runOrderId') || '78901';
        }

        // 加载跑单详情
        async function loadOrderDetails() {
            const runOrderId = getRunOrderId();
            const orderDetailsCard = document.getElementById('orderDetailsCard');
            
            try {
                const response = await fetchWithAuth(`/api/orders/${runOrderId}`);
                
                if (!response.ok) {
                    throw new Error('获取跑单详情失败');
                }
                
                const order = await response.json();
                
                // 渲染跑单详情
                orderDetailsCard.innerHTML = `
                    <div class="order-header">
                        <div class="order-info">
                            <h2>跑单号: <strong>${order.runOrderId}</strong></h2>
                            <div class="order-status">
                                <span>状态:</span>
                                <span class="status-badge status-completed">${getStatusText(order.status)}</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="order-grid">
                        <div class="info-item">
                            <span class="info-label">订单号</span>
                            <span class="info-value">${order.orderId}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">下单用户</span>
                            <span class="info-value">${order.userName}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">配送员</span>
                            <span class="info-value">${order.deliveryPerson}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">完成时间</span>
                            <span class="info-value">${order.completionTime}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">配送地址</span>
                            <span class="info-value">${order.deliveryAddress}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">订单金额</span>
                            <span class="info-value">¥${order.orderAmount || '35.50'}</span>
                        </div>
                    </div>
                `;
            } catch (error) {
                console.error('加载跑单详情出错:', error);
                // 加载失败时显示默认数据
                orderDetailsCard.innerHTML = `
                    <div class="order-header">
                        <div class="order-info">
                            <h2>跑单号: <strong>RUN-${runOrderId}</strong></h2>
                            <div class="order-status">
                                <span>状态:</span>
                                <span class="status-badge status-completed">已完成</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="order-grid">
                        <div class="info-item">
                            <span class="info-label">订单号</span>
                            <span class="info-value">加载中...</span>
                        </div>
                    </div>
                `;
            }
        }

        // 加载评价详情
        async function loadReviewData() {
            const runOrderId = getRunOrderId();
            const reviewContentWrapper = document.getElementById('reviewContentWrapper');
            const noReviewSection = document.getElementById('noReviewSection');
            const reviewForm = document.getElementById('reviewForm');
            
            // 重置显示状态
            reviewContentWrapper.style.display = 'block';
            noReviewSection.style.display = 'none';
            reviewForm.style.display = 'none';
            
            // 显示加载状态
            reviewContentWrapper.innerHTML = `
                <div class="loading">
                    <div class="loading-spinner"></div>
                    <p>加载评价信息中...</p>
                </div>
            `;
            
            try {
                const response = await fetchWithAuth(`/api/reviews/${runOrderId}`);
                
                if (!response.ok) {
                    // 404表示没有评价
                    if (response.status === 404) {
                        reviewContentWrapper.style.display = 'none';
                        noReviewSection.style.display = 'block';
                        return;
                    }
                    throw new Error('获取评价详情失败');
                }
                
                const review = await response.json();
                
                // 渲染评价内容
                reviewContentWrapper.innerHTML = `
                    <div class="review-header">
                        <div class="reviewer-info">
                            <div class="reviewer-avatar">${review.userName ? review.userName.charAt(0) : '用'}</div>
                            <div class="reviewer-details">
                                <h3>${review.userName || '用户'}</h3>
                                <span class="reviewer-level">${review.userLevel || '普通会员'}</span>
                                <div class="review-date">${review.createTime || new Date().toLocaleDateString()}</div>
                            </div>
                        </div>
                        <div class="rating">
                            <div class="rating-score">${review.rating}.0</div>
                            <div class="rating-stars">${getStarHtml(review.rating)}</div>
                        </div>
                    </div>
                    
                    <div class="review-content">
                        ${review.content}
                    </div>
                    
                    ${review.tags ? `
                    <div class="review-tags">
                        ${review.tags.split(',').map(tag => `
                            <span class="review-tag">${tag}</span>
                        `).join('')}
                    </div>
                    ` : ''}
                    
                    ${review.images && review.images.length > 0 ? `
                    <div class="review-media">
                        <div class="media-title">评价图片</div>
                        <div class="media-grid">
                            ${review.images.map((img, index) => `
                                <div class="media-item">
                                    <img src="${img.url || `https://via.placeholder.com/120x120/3498db/FFFFFF?text=${index+1}`}" alt="评价图片${index+1}">
                                </div>
                            `).join('')}
                        </div>
                    </div>
                    ` : ''}
                `;
            } catch (error) {
                console.error('加载评价详情出错:', error);
                // 加载失败时处理
                if (runOrderId === '78907' || runOrderId === '78908') {
                    // 模拟无评价状态
                    reviewContentWrapper.style.display = 'none';
                    noReviewSection.style.display = 'block';
                } else if (runOrderId === '78909') {
                    // 模拟已取消状态
                    reviewContentWrapper.style.display = 'none';
                    noReviewSection.style.display = 'block';
                    document.querySelector('#noReviewSection h3').textContent = '订单已取消';
                    document.querySelector('#noReviewSection p').textContent = '已取消的订单无法评价';
                    document.querySelector('.add-review-btn').style.display = 'none';
                }
            }
        }

        // 获取星级HTML
        function getStarHtml(rating) {
            let html = '';
            for (let i = 1; i <= 5; i++) {
                html += i <= rating ? '★' : '☆';
            }
            return html;
        }

        // 获取状态文本
        function getStatusText(status) {
            const statusMap = {
                'completed': '已完成',
                'pending': '进行中',
                'cancelled': '已取消'
            };
            return statusMap[status] || status;
        }

        // 获取Cookie
        function getCookie(name) {
            const cookieValue = document.cookie
                .split('; ')
                .find(row => row.startsWith(name + '='))
                ?.split('=')[1];
            return cookieValue ? decodeURIComponent(cookieValue) : '';
        }
        
        // 加载用户头像
    function loadUserAvatar() {
        const token = getCookie('jwtToken');
        if (!token) return;
        
        fetch('/api/user/profile', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('获取用户信息失败');
            }
            return response.json();
        })
        .then(data => {
            const userAvatar = document.getElementById('userAvatar');
            if (data.success && data.data && data.data.avatar) {
                let avatarUrl = data.data.avatar;
                
                // 日志记录获取到的头像路径
                console.log('获取到的头像路径:', avatarUrl);
                
                // 确保头像URL格式正确
                // 如果头像路径已经以http开头，直接使用
                if (avatarUrl.startsWith('http')) {
                    userAvatar.src = avatarUrl;
                } 
                // 直接使用file控制器访问头像（现在只存储文件名）
                else {
                    userAvatar.src = '/file/' + avatarUrl;
                    console.log('构建的头像访问URL:', userAvatar.src);
                }
            } else {
                // 如果没有头像，使用默认头像
                userAvatar.src = '/file/default-avatar.png';
                console.log('使用默认头像');
            }
        })
        .catch(error => {
            console.error('加载用户头像失败:', error);
            // 出错时也使用默认头像
            const userAvatar = document.getElementById('userAvatar');
            userAvatar.src = '/file/default-avatar.png';
        });
    }
        
        // 页面加载时执行
        window.addEventListener('DOMContentLoaded', function() {
            // 加载用户头像
            loadUserAvatar();
            // 加载跑单详情
            loadOrderDetails();
            // 加载评价详情
            loadReviewData();
        });
    </script>
</body>
</html>